//
//  FilesViewController.swift
//  GitOSC-Swift
//
//  Created by 李萍 on 16/3/10.
//  Copyright © 2016年 李萍. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class FilesViewController: UITableViewController {
    var nameSpace: String!
    var currentPath: String!
    var files: [GTFiles] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.whiteColor()
        self.fetchProjectsFile()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //tableview 列表
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
        cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
        
        if indexPath.row < files.count {
            let file = files[indexPath.row]
            cell.textLabel?.text = "\(file.fileName)"
            if file.fileType == "tree" {
                cell.imageView?.image = UIImage.init(named: "folder")
            } else {
                cell.imageView?.image = UIImage.init(named: "file")
            }
        }
        
        return cell
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return files.count
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.tableView!.deselectRowAtIndexPath(indexPath, animated: true)
        
        let file = files[indexPath.row]
        if file.fileType == "tree" {
            let filesView = FilesViewController()
            filesView.title = file.fileName
            filesView.nameSpace = self.nameSpace
            filesView.currentPath = "\(file.fileName)"
            self.navigationController?.pushViewController(filesView, animated: true)
        } else {
            print("blob")
        }
        
    }

    //获取数据
    func fetchProjectsFile() -> Void {
        let userinfos = UserInfos()
        let private_token = userinfos.getprivateToken()
        
        let parameters = "path=\(currentPath)&private_token=\(private_token)"
        
        let strUrl = "https://git.oschina.net/api/v3/projects/\(nameSpace)/repository/tree?\(parameters)"
        
        Alamofire.Manager.sharedInstance.request(Method.GET, strUrl).responseJSON { response in
            if let results = response.result.value {
                let jsonArray = JSON(results).array!
                
                for i in 0 ..< jsonArray.count {
                    
                    let file = GTFiles(json: jsonArray[i])
                    self.files.append(file)
                }
                
                self.tableView.reloadData()
            }
        }
    }

}
